<?php

namespace App\Http\Controllers\Api;

use App\Distribution;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\User;
use App\UserInfo;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class DistributionController extends Controller
{
    public function wxShare(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $firstUserId = $request->get('first_user_id');

        /** @var User $isFirstUser */
        $isFirstUser = User::whereId($firstUserId)->first();
        if(!$isFirstUser)
            return response()->json(['level' => 'error','message' => '分享错误！']);

        $thisDistribution = Distribution::whereSecondaryUserId($user->id)->first();
        if(!$thisDistribution){
            $thisDistribution = new Distribution();
            $thisDistribution->first_user_id     = $isFirstUser->id;
            $thisDistribution->secondary_user_id = $user->id;
            $thisDistribution->save();
        }

        return response()->json(['level' => 'success','message' => '成功分享','data' => $thisDistribution]);
    }

    public function inviteUserList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        /** @var Distribution $distribution */
        $distributionList = Distribution::whereFirstUserId($user->id)->orderBy('created_at','desc')->get();
        if(count($distributionList) > 0){
            foreach($distributionList as $distribution){
                /** @var UserInfo $thisUserInfo */
                $thisUserInfo = UserInfo::whereUserId($distribution->secondary_user_id)->first();
                if($thisUserInfo){
                    $distribution->nickname  = $thisUserInfo->nickname;
                    $distribution->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                }else{
                    $distribution->nickname  = null;
                    $distribution->photo_url = null;
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $distributionList]);
    }
}
